import request from '@/utils/request'

// ==================== 接口类型定义 ====================

/**
 * 购物车商品项接口
 */
export interface CartItem {
  cart_id: number
  user: number
  goods: number
  goods_num: number
  selected: boolean
  goods_info: {
    goods_id: number
    goods_name: string
    goods_price: string
    market_price?: string
    goods_cover_img: string
    goods_sales: number
    goods_stock: number
    is_active: boolean
  }
  create_time?: string
  update_time?: string
}

/**
 * 购物车列表响应接口
 */
export interface CartListResponse {
  count: number
  next: string | null
  previous: string | null
  results: CartItem[]
}

/**
 * 添加商品到购物车参数接口
 */
export interface AddToCartParams {
  goods: number
  goods_num: number
}

/**
 * 更新购物车参数接口
 */
export interface UpdateCartParams {
  goods_num: number
  selected: 0 | 1
}

/**
 * 批量选中参数接口
 */
export interface BatchSelectParams {
  cart_ids: number[]
  selected: 0 | 1
}

/**
 * 收藏商品项接口
 */
export interface FavoriteItem {
  favorite_id: number
  goods_id: number
  goods_name: string
  goods_price: string
  goods_cover_img: string
  market_price: string
  goods_sales: number
  create_time: string
}

/**
 * 收藏列表响应接口
 */
export interface FavoriteListResponse {
  list: FavoriteItem[]
  total: number
  total_pages: number
}

/**
 * 检查收藏状态响应接口
 */
export interface CheckFavoriteResponse {
  is_favorited: boolean
  favorite_id?: number
}

/**
 * 分页请求参数接口
 */
export interface PaginationParams {
  page?: number
  page_size?: number
}

/**
 * 检查收藏状态参数接口
 */
export interface CheckFavoriteParams {
  goods_id: number
}

// ==================== API 服务 ====================

/**
 * 购物车API服务
 */
export const cartApi = {
  /**
   * 获取购物车列表
   * GET /cart
   */
  getCartList(): Promise<CartListResponse> {
    return request({
      url: '/cart/',
      method: 'get',
    })
  },

  /**
   * 添加商品到购物车
   * POST /cart
   * @param params - 添加参数
   */
  addToCart(params: AddToCartParams): Promise<any> {
    return request({
      url: '/cart/',
      method: 'post',
      data: params,
    })
  },

  /**
   * 更新购物车商品数量
   * PUT /cart/{cart_id}
   * @param cart_id - 购物车项ID
   * @param params - 更新参数
   */
  updateCartItem(cart_id: number, params: UpdateCartParams): Promise<any> {
    return request({
      url: `/cart/${cart_id}/`,
      method: 'put',
      data: params,
    })
  },

  /**
   * 移除购物车商品
   * DELETE /cart/{cart_id}
   * @param cart_id - 购物车项ID
   */
  removeCartItem(cart_id: number): Promise<any> {
    return request({
      url: `/cart/${cart_id}/`,
      method: 'delete',
    })
  },

  /**
   * 批量选中/取消选中购物车商品
   * POST /cart/check
   * @param params - 批量操作参数
   */
  batchSelectCartItems(params: BatchSelectParams): Promise<any> {
    return request({
      url: '/cart/check/',
      method: 'post',
      data: params,
    })
  },

  /**
   * 清空购物车
   * DELETE /cart/clear
   */
  clearCart(): Promise<any> {
    return request({
      url: '/cart/clear/',
      method: 'delete',
    })
  },
}

/**
 * 收藏API服务
 */
export const favoritesApi = {
  /**
   * 获取收藏列表
   * GET /favorites/
   * @param params - 分页参数
   */
  getFavoritesList(params: PaginationParams = {}): Promise<any> {
    const defaultParams: PaginationParams = {
      page: 1,
      page_size: 10,
    }
    return request({
      url: '/favorites/',
      method: 'get',
      params: { ...defaultParams, ...params },
    })
  },

  /**
   * 添加收藏
   * POST /favorites/{goods_id}
   * @param goods_id - 商品ID
   */
  addToFavorites(goods_id: number): Promise<any> {
    return request({
      url: `/favorites/${goods_id}/`,
      method: 'post',
    })
  },

  /**
   * 取消收藏
   * DELETE /favorites/{goods_id}
   * @param goods_id - 商品ID
   */
  removeFromFavorites(goods_id: number): Promise<any> {
    return request({
      url: `/favorites/${goods_id}/`,
      method: 'delete',
    })
  },

  /**
   * 检查是否收藏
   * GET /favorites/check
   * @param params - 检查参数
   */
  checkFavoriteStatus(params: CheckFavoriteParams): Promise<any> {
    return request({
      url: '/favorites/check/',
      method: 'get',
      params,
    })
  },

  /**
   * 批量取消收藏
   * POST /favorites/batch-remove
   * @param goods_ids - 商品ID数组
   */
  batchRemoveFavorites(goods_ids: number[]): Promise<any> {
    return request({
      url: '/favorites/batch-remove/',
      method: 'post',
      data: { goods_ids },
    })
  },
}

// ==================== 工具函数 ====================

/**
 * 检查商品是否收藏
 */
export const isGoodsFavorited = async (goods_id: number): Promise<boolean> => {
  try {
    const response = await favoritesApi.checkFavoriteStatus({ goods_id })
    return response.data.is_favorited
  } catch (error) {
    console.error('检查收藏状态失败:', error)
    return false
  }
}

/**
 * 切换收藏状态
 */
export const toggleFavoriteStatus = async (
  goods_id: number,
  currentStatus: boolean,
): Promise<boolean> => {
  try {
    if (currentStatus) {
      // 当前已收藏，执行取消收藏
      await favoritesApi.removeFromFavorites(goods_id)
      return false
    } else {
      // 当前未收藏，执行添加收藏
      await favoritesApi.addToFavorites(goods_id)
      return true
    }
  } catch (error) {
    console.error('切换收藏状态失败:', error)
    throw error
  }
}

/**
 * 批量管理收藏商品
 */
export const batchManageFavorites = async (operations: {
  addItems?: number[]
  removeItems?: number[]
}): Promise<void> => {
  try {
    const promises: Promise<any>[] = []

    // 添加收藏
    if (operations.addItems) {
      operations.addItems.forEach((goods_id) => {
        promises.push(favoritesApi.addToFavorites(goods_id))
      })
    }

    // 移除收藏
    if (operations.removeItems) {
      // 如果有批量删除接口，使用批量接口
      if (operations.removeItems.length > 1) {
        promises.push(favoritesApi.batchRemoveFavorites(operations.removeItems))
      } else if (operations.removeItems.length === 1) {
        promises.push(favoritesApi.removeFromFavorites(operations.removeItems[0]))
      }
    }

    await Promise.all(promises)
  } catch (error) {
    console.error('批量操作收藏失败:', error)
    throw error
  }
}

/**
 * 加载收藏列表数据
 */
export const loadFavoritesData = async (
  params: PaginationParams = {},
): Promise<{
  favorites: FavoriteItem[]
  total: number
  totalPages: number
}> => {
  try {
    const response = await favoritesApi.getFavoritesList(params)
    return {
      favorites: response.data.list,
      total: response.data.total,
      totalPages: response.data.total_pages,
    }
  } catch (error) {
    console.error('加载收藏列表失败:', error)
    throw error
  }
}

/**
 * 验证收藏数据
 */
export const validateFavoritesData = (
  favorites: FavoriteItem[],
): {
  validItems: FavoriteItem[]
  invalidItems: FavoriteItem[]
} => {
  const validItems: FavoriteItem[] = []
  const invalidItems: FavoriteItem[] = []

  // 这里可以根据业务需求添加验证逻辑
  // 例如：检查商品是否下架、是否存在等
  favorites.forEach((item) => {
    // 简单的示例验证：检查必要字段是否存在
    if (item.goods_id && item.goods_name) {
      validItems.push(item)
    } else {
      invalidItems.push(item)
    }
  })

  return { validItems, invalidItems }
}

/**
 * 格式化价格（将字符串转为数字）
 */
export const formatPrice = (price: string | number): number => {
  if (typeof price === 'number') return price
  return parseFloat(price) || 0
}

/**
 * 计算购物车选中商品总价
 */
export const calculateSelectedTotalPrice = (cartList: CartItem[]): number => {
  return cartList.reduce((total, item) => {
    if (item.selected === true) {
      return total + formatPrice(item.goods_info.goods_price) * item.goods_num
    }
    return total
  }, 0)
}

/**
 * 计算购物车选中商品总数
 */
export const calculateSelectedTotal = (cartList: CartItem[]): number => {
  return cartList.reduce((total, item) => {
    if (item.selected === true) {
      return total + item.goods_num
    }
    return total
  }, 0)
}

/**
 * 检查购物车商品是否全部选中
 */
export const isAllSelected = (cartList: CartItem[]): boolean => {
  if (cartList.length === 0) return false
  return cartList.every((item) => item.selected === true)
}

/**
 * 检查购物车商品是否有选中
 */
export const hasSelectedItems = (cartList: CartItem[]): boolean => {
  return cartList.some((item) => item.selected === true)
}

/**
 * 获取选中的购物车商品ID列表
 */
export const getSelectedCartIds = (cartList: CartItem[]): number[] => {
  return cartList.filter((item) => item.selected === true).map((item) => item.cart_id)
}

/**
 * 获取选中的购物车商品列表
 */
export const getSelectedCartItems = (cartList: CartItem[]): CartItem[] => {
  return cartList.filter((item) => item.selected === true)
}

/**
 * 检查商品库存是否充足
 */
export const checkStock = (item: CartItem): boolean => {
  return item.goods_num <= item.goods_info.goods_stock && item.goods_info.is_active
}

/**
 * 检查购物车中是否存在某个商品
 */
export const isGoodsInCart = (cartList: CartItem[], goods_id: number): boolean => {
  return cartList.some((item) => item.goods === goods_id)
}

/**
 * 根据商品ID获取购物车中的商品
 */
export const getCartItemByGoodsId = (
  cartList: CartItem[],
  goods_id: number,
): CartItem | undefined => {
  return cartList.find((item) => item.goods === goods_id)
}

// ==================== 高级工具函数 ====================

/**
 * 批量操作购物车商品
 */
export const batchCartOperations = async (operations: {
  addItems?: AddToCartParams[]
  updateItems?: { cart_id: number; params: UpdateCartParams }[]
  removeItems?: number[]
}): Promise<void> => {
  try {
    const promises: Promise<any>[] = []

    // 添加商品
    if (operations.addItems) {
      operations.addItems.forEach((item) => {
        promises.push(cartApi.addToCart(item))
      })
    }

    // 更新商品
    if (operations.updateItems) {
      operations.updateItems.forEach(({ cart_id, params }) => {
        promises.push(cartApi.updateCartItem(cart_id, params))
      })
    }

    // 移除商品
    if (operations.removeItems) {
      operations.removeItems.forEach((cart_id) => {
        promises.push(cartApi.removeCartItem(cart_id))
      })
    }

    await Promise.all(promises)
  } catch (error) {
    console.error('批量操作购物车失败:', error)
    throw error
  }
}

/**
 * 全选/取消全选购物车商品
 */
export const toggleAllCartItems = async (cartList: CartItem[], selected: 0 | 1): Promise<void> => {
  if (cartList.length === 0) return

  const cart_ids = cartList.map((item) => item.cart_id)
  await cartApi.batchSelectCartItems({ cart_ids, selected })
}

/**
 * 添加或更新购物车商品
 */
export const addOrUpdateCartItem = async (
  goods_id: number,
  goods_num: number,
  cartList: CartItem[],
): Promise<void> => {
  const existingItem = getCartItemByGoodsId(cartList, goods_id)

  if (existingItem) {
    // 如果商品已存在，更新数量
    const selectedNum = existingItem.selected ? 1 : 0
    const newQuantity = existingItem.goods_num + goods_num
    await cartApi.updateCartItem(existingItem.cart_id, {
      goods_num: newQuantity,
      selected: selectedNum,
    })
  } else {
    // 如果商品不存在，添加新商品
    await cartApi.addToCart({ goods: goods_id, goods_num })
  }
}

/**
 * 验证购物车数据
 */
export const validateCartData = (
  cartList: CartItem[],
): {
  isValid: boolean
  errors: string[]
  outOfStockItems: CartItem[]
  inactiveItems: CartItem[]
} => {
  const errors: string[] = []
  const outOfStockItems: CartItem[] = []
  const inactiveItems: CartItem[] = []

  cartList.forEach((item) => {
    if (!checkStock(item)) {
      outOfStockItems.push(item)
      errors.push(`商品 "${item.goods_info.goods_name}" 库存不足`)
    }

    if (!item.goods_info.is_active) {
      inactiveItems.push(item)
      errors.push(`商品 "${item.goods_info.goods_name}" 已下架`)
    }
  })

  return {
    isValid: errors.length === 0,
    errors,
    outOfStockItems,
    inactiveItems,
  }
}

/**
 * 加载购物车数据并验证
 */
export const loadAndValidateCart = async (): Promise<{
  cartData: CartListResponse
  validation: ReturnType<typeof validateCartData>
}> => {
  try {
    const response = await cartApi.getCartList()
    const cartData = response
    const validation = validateCartData(cartData.results)

    return {
      cartData,
      validation,
    }
  } catch (error) {
    console.error('加载购物车数据失败:', error)
    throw error
  }
}

/**
 * 准备结算数据
 */
export const prepareCheckoutData = (
  cartList: CartItem[],
): {
  validItems: CartItem[]
  invalidItems: CartItem[]
  totalAmount: number
  totalQuantity: number
} => {
  const validation = validateCartData(cartList)
  const validItems = cartList.filter(
    (item) => checkStock(item) && item.goods_info.is_active && item.selected === true,
  )
  const invalidItems = cartList.filter((item) => !checkStock(item) || !item.goods_info.is_active)

  const totalAmount = calculateSelectedTotalPrice(validItems)
  const totalQuantity = calculateSelectedTotal(validItems)

  return {
    validItems,
    invalidItems,
    totalAmount,
    totalQuantity,
  }
}

// ==================== 默认导出 ====================

export default { cartApi, favoritesApi }
